package com.gcloud.mesh.dcs.dataclean.handle;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.gcloud.mesh.framework.core.SpringUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ConsumerHandleManager {

	private static final Map<String, IHandler> HANDLERS = new HashMap<>();
	
	private static final Map<String, Class> CLASSES = new HashMap<>();
    
    @PostConstruct
    public void init() throws Exception {
        for (Map.Entry<String, IHandler> entry : SpringUtil.getBeansOfType(IHandler.class).entrySet()) {
            String action = entry.getKey();
            IHandler handler = entry.getValue();
            action = action.substring(0, 1).toUpperCase() + action.substring(1, action.length() - "Handler".length());
            HANDLERS.put(action, handler);
            log.info("[ConsumerHandleManager] register Handler {} {}", action, handler.getClass());
            for (Type i : handler.getClass().getGenericInterfaces()) {
                if (i.getTypeName().split("<")[0].equals("com.gcloud.mesh.dcs.dataclean.handle.IHandler")) {
                    Type[] t = ((ParameterizedType)i).getActualTypeArguments();
                    CLASSES.put(action, (Class)t[0]);
                    log.info("[ConsumerHandleManager] register Class {} {}", action, ((Class)t[0]).getCanonicalName());
                    break;
                }
            }
        }
    }
    
    public static IHandler getHandler(String action) {
        return HANDLERS.get(action);
    }
    
    public static Class getClass(String action) {
        return CLASSES.get(action);
    }
    
}
